package com.stars.control.user.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.stars.base.constants.SystemConstants;
import com.stars.base.constants.SystemSettingConstants;
import com.stars.base.entity.CommonDTO;
import com.stars.base.entity.TreeNode;
import com.stars.base.entity.UserSelectDTO;
import com.stars.control.user.service.StarUserSelectService;
import com.stars.module.department.entity.StarDept;
import com.stars.module.department.mapper.StarDeptMapper;
import com.stars.module.user.entity.StarOrgUser;
import com.stars.module.user.entity.StarUser;
import com.stars.module.user.mapper.OrgUserMapper;
import com.stars.module.user.mapper.UserMapper;
import com.stars.util.common.DevelopKit;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class StarUserSelectServiceImpl implements StarUserSelectService {

    private final StarDeptMapper deptMapper;
    private final UserMapper userMapper;
    private final OrgUserMapper orgUserMapper;

    public StarUserSelectServiceImpl(StarDeptMapper deptMapper, UserMapper userMapper,OrgUserMapper orgUserMapper) {
        this.deptMapper = deptMapper;
        this.userMapper = userMapper;
        this.orgUserMapper = orgUserMapper;
    }


    @Override
    public JSONArray data(HttpServletRequest request) {

        String customRoot = request.getParameter("customRoot");

        JSONArray array = new JSONArray();
        TreeNode node;

        if(!org.springframework.util.StringUtils.hasLength(customRoot)){
//            customRoot = user. // TODO 从session取用户机构id，现用户里面没有存

            LambdaQueryWrapper<StarDept> query = new LambdaQueryWrapper<>();
            query.eq(StarDept::getFid, "0");

            StarDept unit = deptMapper.selectOne(query);

            customRoot = unit.getId();

            node = new TreeNode();

            node.setValue(unit.getId());
            node.setLabel(unit.getOrgName());
            node.setpId(unit.getFid());
            node.setIsLeaf(false);// 是否叶子节点

            JSONObject attr = new JSONObject();
            attr.put("type", "unit");
            node.setAttr(attr);

            array.add(node);
        }

        //子用户
        CommonDTO dto = new CommonDTO();
        dto.setFid(customRoot);
        List<StarUser> users = userMapper.loadUserByDeptId(dto, null);
        for(StarUser entity: users){
            node = new TreeNode();

            node.setValue(entity.getId());
            node.setLabel(entity.getName());
            node.setpId(customRoot);
            node.setIsLeaf(true);// 是否叶子节点，用户都是

            JSONObject attr = new JSONObject();
            attr.put("type", "user");

            node.setAttr(attr);

            array.add(node);
        }

        //子部门
        LambdaQueryWrapper<StarDept> query = new LambdaQueryWrapper<>();
        query.eq(StarDept::getFid, customRoot);
        query.orderByAsc(StarDept::getShowOrder);

        List<StarDept> deptList = deptMapper.selectList(query);

        for(StarDept entity: deptList){
            node = new TreeNode();

            node.setValue(entity.getId());
            node.setLabel(entity.getOrgName());
            node.setpId(entity.getFid());
            node.setIsLeaf(false);// 是否叶子节点，部门默认都不是

            JSONObject attr = new JSONObject();
            attr.put("type", "dept");

            node.setAttr(attr);

            array.add(node);
        }

        return array;
    }

    /**
     * 加载用户树
     */
    @Override
    public JSONObject loadAllUserTree(@RequestBody UserSelectDTO dto) {
        JSONObject array = new JSONObject();

        List<TreeNode> treeNodes = new ArrayList<>();
        if(StringUtil.isBlank(dto.getFid()) && StringUtil.isBlank(dto.getSearch())){
            TreeNode rootNode = new TreeNode();
            rootNode.setId(SystemConstants.ROOT_UNITID);
            rootNode.setLabel(DevelopKit.getStringFromDBConfig(SystemSettingConstants.SYS_ROOT_UNIT_NAME));
            rootNode.setValue(SystemConstants.ROOT_UNITID);
            rootNode.setpId("0");
            treeNodes.add(rootNode);
        }else{
            if(StringUtil.isBlank(dto.getSearch())){
                handleTreeNodes(dto,treeNodes);
            }else{
                handleSearchTreeData(dto,treeNodes);
            }
        }
        array.put("data",treeNodes);
        return array;
    }

    /**
     * 检索用户树
     */
    private void handleSearchTreeData(UserSelectDTO dto,List<TreeNode> treeNodes){
        /*处理用户*/
        List<StarOrgUser> searchUser  = orgUserMapper.loadUserDetail(dto);

        Set<String> orgIds = new HashSet<>();
        String deptId;
        if(!searchUser.isEmpty()){
            for(StarOrgUser user : searchUser){
                deptId = user.getCreateDeptId();
                if(!orgIds.contains(deptId)){
                    orgIds.add(deptId);
                    TreeNode node = new TreeNode();
                    node.setId(user.getCreateDeptId());
                    node.setValue(user.getCreateDeptId());
                    node.setpId("0");
                    node.setLabel(user.getOrgName());
                    node.setIsLeaf(false);
                    node.setChildren(getChildNodes(deptId,searchUser));
                    treeNodes.add(node);
                }
            }
        }
    }

    private List<TreeNode> getChildNodes(String deptId,List<StarOrgUser> searchUser){
        List<TreeNode> childNodes = new ArrayList<>();
        for(StarOrgUser user : searchUser){
            if(deptId.equals(user.getCreateDeptId())){
                TreeNode node = new TreeNode();
                node.setId(user.getId());
                node.setValue(user.getId());
                node.setpId(deptId);
                node.setLabel(user.getName());
                node.setIsLeaf(true);
                childNodes.add(node);
            }
        }
        return childNodes;
    }
    /**
     * 默认用户树
     */
    private void handleTreeNodes(UserSelectDTO dto,List<TreeNode> treeNodes){
        List<String> tags = dto.getTags();
        if(tags==null){
            tags = new ArrayList<>();
            tags.add("user");
        }
        tags.forEach((item)->{
            if("user".equals(item)){
                handleUser(dto,treeNodes);
                handleDept(dto,treeNodes,false);
            }else if("dept".equals(item)){
                handleDept(dto,treeNodes,true);
            }
        });
    }

    /**
     * 拉取用户
     */
    private void handleUser(UserSelectDTO dto,List<TreeNode> treeNodes){
        /*处理用户*/
        List<StarUser> listUser = userMapper.selectJoinList(StarUser.class,new MPJLambdaWrapper<StarUser>()
                .selectAll(StarUser.class)
                .leftJoin(StarOrgUser.class,StarOrgUser::getUserId,StarUser::getId)
                .eq(StarOrgUser::getOrgId,dto.getFid())
                .eq(StarUser::getRowStatus,1)
                .ne(StarUser::getId,"1")
                .orderByAsc(StarUser::getShowOrder));

        if(!listUser.isEmpty()){
            for(StarUser user : listUser){
                TreeNode node = new TreeNode();
                node.setId(user.getId());
                node.setValue(user.getId());
                node.setpId(dto.getFid());
                node.setLabel(user.getName());
                node.setIsLeaf(true);
                JSONObject att = new JSONObject();
                att.put("deptId",user.getCreateDeptId());
                node.setAttr(att);
                treeNodes.add(node);
            }
        }
    }

    /**
     * 组装部门数据
     * @param isOnly 是否只选，只选部门需要将leaf置为true
     */
    private void handleDept(UserSelectDTO dto,List<TreeNode> treeNodes,boolean isOnly){
        /*处理部门*/
        List<StarDept> allDeptArr = getChildDept(dto.getSearch(),dto.getFid());

        for(StarDept dept : allDeptArr){

            TreeNode node = new TreeNode();
            node.setId(dept.getId());
            node.setValue(dept.getId());
            node.setpId(dept.getFid());
            node.setLabel(dept.getOrgName());
            if(isOnly && getChildDept("", dept.getId()).isEmpty()){
                node.setIsLeaf(true);
            }
            treeNodes.add(node);
        }
    }

    /**
     * 获取子部门
     */
    private List<StarDept> getChildDept(String search,String fid){
        LambdaQueryWrapper<StarDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StarDept::getOrgName,search);
        wrapper.eq(StarDept::getFid, fid);
        wrapper.eq(StarDept::getIsUnit,-1);
        wrapper.orderByAsc(StarDept::getShowOrder);

        return Optional.ofNullable(deptMapper.selectList(wrapper)).orElse(Collections.emptyList());
    }
}
